//
//  ViewController.m
//  屏幕截图
//
//  Created by fanxiao on 16/3/19.
//  Copyright © 2016年 尚宇电子. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, 100, 110)];
    backView.backgroundColor = [UIColor redColor];
    [self.view addSubview:backView];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 5, 70, 70)];
    imageView.image = [UIImage imageNamed:@"havinglook_cancel.png"];
    [backView addSubview:imageView];
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(10, 85, 70, 20)];
    lbl.text = @"屏幕截图";
    [backView addSubview:lbl];
    
    UIImage *newImage = [self shortScreenOfAnyView:backView];
    
    //5.保存到沙盒中
    NSData *imgData = UIImagePNGRepresentation(newImage);
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *imgPath = [doc stringByAppendingPathComponent:@"test12.png"];
    [imgData writeToFile:imgPath atomically:YES];
    
}

/**
 *  截屏
 *  @param backView 要截屏的父控件
 *  @return 返回父控件中所有的子控件的截图(PNG图片，不会失真)
 */
-(UIImage*)shortScreenOfAnyView:(UIView*)backView
{
    UIGraphicsBeginImageContextWithOptions(backView.bounds.size, NO, 0.0);
    
    //2.将当前控制器的view的图层渲染到当前的上下文中
    [backView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    //3.获取当前上下文中的新图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //4.结束位图编辑
    UIGraphicsEndImageContext();

    return newImage;
}
@end
